package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"yk1/models"
)

type Usercontroller struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *Usercontroller) Register() {
	username := c.GetString("username")
	password := c.GetString("password")

	user := models.User{
		Username: username,
		Password: Md5(password),
	}

	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "账号密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "注册成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *Usercontroller) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "账号密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Where("username = ?", username).First(username).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误次数过多,账号封禁2小时",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "登录成功",
			Data: models.User{},
		}
		c.ServeJSON()
	}

	if password != Md5(password) {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
